package com.comum.javahomework420242025.filter;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;

import java.io.IOException;

@WebFilter("/*")
@Component
public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String url = req.getRequestURI().toString();
        if(url.contains("login")){
            filterChain.doFilter(servletRequest,servletResponse);//放行
        }
        else{
            HttpSession session = req.getSession();
            Object token = session.getAttribute("token");
            if(token!=null){
                filterChain.doFilter(servletRequest,servletResponse);//有token放行
            }
            else{
                resp.setStatus(401);//设置状态码，方便前端判断是否登录，并给出相应提示
            }
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
